package com.zlyx.easy.database.local;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * @Auth 赵光
 * @Describle
 * @2019年1月9日 上午9:05:00
 */
public class ReturnType {

	private static ThreadLocal<Class<?>> type = new ThreadLocal<Class<?>>();

	/**
	 * 设置需要返回的实体类类型
	 * 
	 * @param clazz
	 */
	public static void setType(Class<?> clazz) {
		type.set(clazz);
	}

	public static void setType(Method method) {
		Type type = getReturnType(method);
		if (type == null || type.getClass().getName().startsWith("sun.reflect.generics")) {
			setType(Map.class);
		} else {
			setType((Class<?>) type);
		}
	}

	public static Class<?> getType() {
		return type.get();
	}

	public static void clear() {
		type.remove();
	}

	public static Type getReturnType(Method method) {
		if (method.getReturnType() != List.class && method.getReturnType() != Page.class) {
			return method.getReturnType();
		}
		Type type = method.getGenericReturnType();
		if (type instanceof ParameterizedType) {
			Type[] types = ((ParameterizedType) type).getActualTypeArguments();
			if (types.length > 0) {
				return types[0];
			}
		}
		return null;
	}
}
